import {BASE_URL, LOCK_ENUM, STATUS_HEIGHT} from "../../constant/index";
import {toast} from "../../utils/tool";
import EventBus from "../../utils/eventBus";

const app = getApp()
// 登录 ==>  获取定位 ==>  检查是否存在缓存选中店铺 存在 ==>初始化包间信息 /不存在 ==> 初始化选中门店 ==> 初始化包间信息
Page({
    data: {
        initCount: 0,
        showShare: false,
        shareID: '',
        flag: false,
        text: '',
        statusHeight: 322,
        show: false,
        showLock: false,
        roomPop: false,
        bookstore: {},
        // 默认店铺的距离
        firstDis: '',
        // 弹窗是否显示
        popshow: false,
        // 卡片项数据
        firstStore: {}, //置顶门店
        cardData: [], //门店包间的数据
        storeList: [], //门店列表数据
        latitude: "", //纬度
        longitude: "", //经度
        user: {},
        city: {},
        lat: '',
        lon: '',
        order_id: 0,
        stores: [],
        banner: wx.getStorageSync('banner_data') || [], //首页轮播图
        // 预定组件的显示与隐藏
        bookshow: false,
        storeshow: false,
        // 时间数据
        times: {},
        allTimes: [],
        logoUrl: '',
        //确认的开始时间
        confirmTime: '',
        confirmEndTime: '',
        select_date: '',
        select_start: '',
        select_end: '',
        nums: 0,
        date_arr: [],
        id: '', //门店id
        advert: '',
        imgUrl: BASE_URL,
        showCalc: false,
        showLocationPop: false,
    },
    closeLayer() {
        this.setData({
            bookshow: false
        })
    },
    toGroupBuying() {
        wx.navigateTo({
            url: '/pages/group-buying/group-buying'
        })
    },
    closeCalc() {
        this.setData({
            showCalc: false
        })
    },
    validateCoupon() {
        wx.showModal({
            title: '提示',
            showCancel: false,
            content: '温馨提示，如需抖音、美团验券，请先点击“包厢列表”选择对应的“包厢”和“时长”，在最下方支付方式中选择“团购验券”即可。'
        })
    },

    initLogoUrl() {
        app.ajax({
            url: '/api/banner/indexlogo',
            success: resp => {
                if (resp.code !== 1) return
                this.setData({
                    logoUrl: BASE_URL + resp.data
                })
            }
        })
    },
    bookcancel() {
        this.setData({
            bookshow: false
        })
    },
    toUrl(ev) {
        const {path} = ev.currentTarget.dataset
        if (!!path) {
            wx.navigateTo({
                url: path
            })
        }
    },
    initRect() {
        let selector = wx.createSelectorQuery()
        selector.select('#headerBody').boundingClientRect(rect => {
            const {height} = rect
            this.setData({
                statusHeight: STATUS_HEIGHT + height
            })
        }).exec()
        selector = null
    },
    // 我要加盟
    jiameng() {
        wx.navigateTo({
            url: '/pages/join/join',
        })
    },
    // 公告
    getVoice() {
        // app.ajax({
        //     url: '/api/index/advert',
        //     data: {},
        //     success: res => {
        //         if (res.code == 1) {
        //             this.setData({
        //                 advert: res.data
        //             })
        //         }
        //     }
        // })
    },
    openHand() {
        this.setData({
            showLock: true
        })
    },
    // 打开地图
    openMap: function () {
        let arr = this.data.firstStore.lat.split(",")
        const lat = parseFloat(arr[1]),
            lon = parseFloat(arr[0]),
            firstStore = this.data.firstStore;
        if (!lat || !lon) {
            return false;
        }
        wx.openLocation({
            latitude: lon,
            longitude: lat,
            scale: 15,
            name: firstStore.name,
            address: firstStore.address,
            success: function (res) {
            },
            fail: function (res) {
            }
        })
    },
    // 开包间房门
    opensmall() {
        wx.switchTab({
            // url:"/pages/my-reserve/my-reserve",
            url: '/pages/my-order/my-order',
        })
    },
    // 开大门
    openDoor() {
        const {firstStore: {id}} = this.data
        app.ajax({
            url: '/api/frontdoor/openfrontdoor',
            data: {
                store_id: id
            },
            success: res => {
                toast({title: res.msg})
            }
        })
    },
    // 获取门店
    getfirst() {
        const {lat, lon} = this.data
        app.ajax({
            url: '/api/room/storebyplace',
            data: {lon, lat},
            success: res => {
                if (!res.data.length) return toast({title: '没有获取到门店'})
                const [activeStore] = res.data
                app.setFirst(activeStore)
                this.setData({
                    firstStore: activeStore,
                })
                const {id} = activeStore
                this.findRooms(id)
                this.getBanner(id)
            }
        })
    },
    // 弹框关闭
    handlecancel() {
        this.setData({
            popshow: false
        })
    },
    // 预订选择时间
    stopBubb: function () {
        return false
    },
    getSelectedTimes: function () {
        app.ajax({
            url: '/api/index/getAllTImes',
            data: {
                id: this.data.id,
                date: this.data.select_date
            },
            success: res => {
                if (res.code == 1) {
                    this.setData({
                        allTimes: res.data
                    })
                    this.getTimes()
                }
            }
        }, 1);
    },
    getTimes: function () {
        var datenow = this.data.select_date;
        datenow = datenow.replace(/-/g, "/")
        var start = new Date(datenow + ' 00:00:00').getTime().toString()
        start = start.substr(0, 10)
        start = parseInt(start)
        var end = start + 60 * 60 * 24 - 1
        // var end = start + (60 * 60 * 24) * 2
        var times = {}
        const {allTimes} = this.data
        const _end = end + 60 * 60 * 24 - 1
        for (let key in allTimes) {
            if (key >= start && key <= end) {
                const target = allTimes[key]
                target.isNext = false
                times[key] = target
            }
            // 找到第二天的
            if (key >= end && key <= _end) {
                const target = allTimes[key]
                target.isNext = true
                times[key] = target
            }
        }
        this.setData({
            times: times
        })
    },

    selectTime: function (e) {
        var times = this.data.allTimes,
            index = parseInt(e.currentTarget.dataset.index),
            time = e.currentTarget.dataset.time,
            select_start = this.data.select_start,
            select_end = this.data.select_end;
        if (times[index].disabled) {
            return false;
        }
        if (select_start !== '' && select_end !== '') {
            for (let i in times) {
                times[i].select = false;
            }
            times[index].select = true;
            this.setData({
                select_start: index,
                select_end: '',
                nums: 0,
                allTimes: times
            })
        } else if (select_start !== '') {
            if (select_start == index) {
                times[index].select = false;
                this.setData({
                    select_start: '',
                    allTimes: times
                });
                return false;
            } else if (index > select_start) {
                select_end = index;
            } else {
                select_end = select_start;
                select_start = index;
            }
            var error = false,
                nums = 0;
            for (let i in times) {
                times[i].select = false;
                if (i >= select_start && i <= select_end) {
                    if (times[i].disabled) {
                        error = true;
                    }
                    times[i].select = true;
                    nums += 1;
                }
            }
            if (nums > 0) nums -= 1;
            if (error) {
                wx.showToast({
                    title: '存在不可选项',
                    icon: 'none'
                });
                return false;
            }
            this.setData({
                select_start: select_start,
                select_end: select_end,
                allTimes: times,
                nums: nums
            })
        } else {
            times[index].select = true;
            this.setData({
                allTimes: times,
                select_start: index
            })
        }
        this.getTimes()
    },
    // 切换门店
    changestore() {
        wx.navigateTo({
            url: '/pages/changestore/changestore?type=back',
        })
    },

    // 查询全部店铺
    getStore() {
        const {lat, lon} = this.data
        let params = {}
        if (!!lat && !!lon) {
            params.lat = lat
            params.lon = lon
        }
        app.ajax({
            url: "/api/room/storelist",
            data: params,
            success: res => {
                this.setData({
                    storeList: res.data
                })
            }
        })
    },
    // 时间组件
    // 点击tab切换
    swichNav: function (e) {
        var date = e.currentTarget.dataset.date;
        if (this.data.select_date == date) {
            return false;
        } else {
            this.setData({
                select_date: date
            });
            this.getTimes();
        }
    },
    getDate: function (now) {
        var date = new Date(now),
            y = date.getFullYear(),
            m = date.getMonth() + 1,
            w = date.getDay(),
            d = date.getDate(),
            weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        m = ('0' + m).slice(-2);
        d = ('0' + d).slice(-2);
        return {
            week: weeks[w],
            date: y + '-' + m + '-' + d,
            name: m + '.' + d
        };
    },
    tochongzhi() {
        this.setData({
            bookshow: false,
        })
        wx.navigateTo({
            url: '/pages/group-buying/group-buying',
        })
    },
    confirm_book: function () {
        var data = this.data.bookstore;
        var data1 = this.data.allTimes;
        let newdata = encodeURIComponent(JSON.stringify(data))
        let times = encodeURIComponent(JSON.stringify(data1))
        const c = this.data.nums
        const flag = c < 4
        if (flag) {
            return toast({title: '定时间两小时起'})
        }
        const id_str = `&id=${this.data.id}`
        wx.navigateTo({
            url: '/pages/book/book?newdata=' + newdata + '&selectstart=' + this.data.select_start +
                '&selectend=' + this.data.select_end + '&nums=' + this.data.nums + '&times=' + times + '&type=bookTime' + id_str
        })
    },
    // 接收子组件的传参
    booktime(e) {
        const hasMobile = app.checkHasMobile()
        if (!hasMobile) return
        this.setData({
            bookshow: true,
            id: e.detail.id,
            bookstore: e.detail
        })
        this.getSelectedTimes()
    },
    calcHandler() {
        this.setData({
            showCalc: true
        })
    },
    // 美团验券
    meituan: function () {
        wx.navigateTo({
            url: '/pages/group-buying/group-buying?type=' + 2
        })
    },
    formatTime(timestamp) {
        const date = new Date(timestamp)
        const [hour, minutes] = [date.getHours(), date.getMinutes()]
        return `${('0' + hour).slice(-2)}:${('0' + minutes).slice(-2)}`
    },
    getTimeLine(useTimes = []) {
        const date = new Date()
        const [hour] = [date.getHours()]
        const result = []
        let timeValue = hour
        for (let i = 1; i < 25; i++) {
            if (timeValue >= 24) {
                timeValue = 0
            }
            result.push({
                time: timeValue,
                use: useTimes.includes(i),
                index: i,
            })
            timeValue += 1
        }
        return result
    },
    // 查询 门 店的包间
    findRooms(storeid) {
        app.ajax({
            url: "/api/room/selcetroombystore",
            data: {storeid},
            success: res => {
                if (!res.data || !res.data.length) {
                    toast({title: '该门店没有包间数据'})
                    res.data = []
                }
                // app.setRoomList(res.data)
                const useStatus = [2, 3, 4]
                const textEnum = {1: '空闲中,可预订', 3: '待 保 洁', 4: '正在保洁中'}
                const roomList = res.data.map(item => {
                    let {roomtime} = item
                    const {status, end_time, room_tags, tuijian_taocan} = item
                    if (!roomtime) roomtime = []
                    const useTimes = roomtime.map(item => item.time * 1)
                    item.timeLine = this.getTimeLine(useTimes)
                    if (!room_tags) {
                        item.room_tags = []
                    } else {
                        item.room_tags = room_tags.split(',').filter(Boolean)
                    }
                    const _status = Number(status)
                    item.show_status = useStatus.includes(_status)
                    const showTime = _status === 2 && !isNaN(end_time)
                    let status_text = ''
                    if (showTime) {
                        status_text = `使用中 ${this.formatTime(end_time * 1000)}结束`
                    } else {
                        status_text = textEnum[_status]
                    }
                    item.status_text = status_text
                    item.showMeal = !!tuijian_taocan
                    return item
                })
                this.setData({
                    cardData: roomList,
                })
            }
        })
    },
    // 获取首页轮播图
    getBanner(store_id) {
        app.ajax({
            url: '/api/banner/bannerlist',
            data: {
                type: 1,
                store_id,
            },
            success: res => {
                res.data = res.data || []
                wx.setStorageSync('banner_data', res.data)
                this.setData({
                    banner: res.data
                })
            }
        })
    },
    // 开大门
    async openDoorBig() {
        let self = this
        self.setData({
            popshow: true
        })
    },
    clear() {
        this._failNums = 0;
        /* 设置traceId */
    },
    history_order: function () {
        wx.navigateTo({
            url: '/pages/history_order/history_order'
        })
    },
    callPhone(e) {
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.phone,
            success: function () {
            },
        })
    },
    join: function () {
        wx.navigateTo({
            url: '/pages/my_order/my_order'
        })
    },
    initText() {
        const {showFlag} = app.globalData
        if (showFlag) return
        app.ajax({
            url: "/api/content/indexshuoming",
            success: resp => {
                const {data} = resp
                app.globalData.showFlag = true
                this.setData({
                    text: data,
                    show: true,
                });
            }
        })
    },
    openShare() {
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
    },
    onShareAppMessage() {
        const promise = new Promise(resolve => {
            setTimeout(() => {
                resolve({
                    title: '博戏互娱',
                    path: '/pages/index/index',
                })
            }, 2000)
        })
        return {
            title: '博戏互娱',
            path: '/pages/index/index',
            promise
        }
    },
    checkIsShare(options) {
        if (!options || !options.hasOwnProperty('type')) return this.initText()
        const {id} = options
        // toast({title: 'id' + id})
        this.setData({
            // shareID: options.id,
            shareID: id,
            showShare: true,
        })
    },
    shareConfirm() {
        this.setData({
            showShare: false,
        })
        this.initText()
        wx.switchTab({
            url: '/pages/index/index'
        })
    },
    initSelectTime() {
        const date_arr = [];
        for (let i = 0; i < 5; i++) {
            let now = new Date().getTime() + i * 86400000;
            date_arr.push(this.getDate(now));
        }
        let start_date = this.getDate(Date.now() + 86400000 * 5),
            end_date = this.getDate(Date.now() + 86400000 * 7);
        this.setData({
            date_arr: date_arr,
            date_start: start_date.date,
            date_end: end_date.date,
            select_date: date_arr[0].date
        });
    },
    checkJoinType() {
        const {indexType, selectStore} = app.globalData
        if (indexType === 1 && !!selectStore) {
            return this.setData({
                firstStore: selectStore
            })
        }
        app.getUserInfo().then(() => {
            this.getLocation(false);
        })
    },
    onLoad: function (options) {
        this.openShare()
        this.initLogoUrl()
        this.initRect()
        // app.getUserInfo().then(() => {
        this.checkIsShare(options)
        this.checkJoinType()
        // this.getLocation(false);
        this.initSelectTime()
        this.getSite();
        // })
        EventBus.$on('changeStore', this.changeStoreSuccess)
    },
    onUnload() {
        EventBus.$off('changeStore', this.changeStoreSuccess)
    },
    getSite: function () {
        app.ajax({
            url: '/api/index/getSite',
            success: res => {
                if (res.code === 1) {
                    const site = res.data;
                    wx.setStorageSync('tel', site.tel);
                    // wx.setStorageSync('instructions', site.instructions);
                    // wx.setStorageSync('about', site.about);
                    wx.setStorageSync('disclaimer', site.disclaimer);
                    // wx.setStorageSync('explain', site.explain);
                }
            }
        })
    },
    onSetting() {
        this.setData({
            showLocationPop: false,
        })
        this.getUserLocation(false)
    },
    getUserLocation(flag) {
        wx.getLocation({
            type: 'gcj02',
            success: res => {
                this.data.lat = res.latitude.toString()
                this.data.lon = res.longitude.toString()
                wx.setStorageSync('location', {
                    lat: res.latitude,
                    lon: res.longitude
                });
                if (!flag) {
                    this.getfirst()
                }
            },
            fail: () => {
                this.getfirst()
            }
        })
    },
    getLocation: function (flag) {
        wx.authorize({
            scope: 'scope.userLocation',
            success: () => {
                this.getUserLocation(false)
            },
            fail: () => {
                this.setData({
                    showLocationPop: true,
                })
            }
        })
        // wx.getLocation({
        //     type: 'gcj02',
        //     success: res => {
        //         console.log(res, 'location')
        //         this.data.lat = res.latitude.toString()
        //         this.data.lon = res.longitude.toString()
        //         // this.setData({
        //         //     lat: res.latitude.toString(),
        //         //     lon: res.longitude.toString(),
        //         // });
        //         wx.setStorageSync('location', {
        //             lat: res.latitude,
        //             lon: res.longitude
        //         });
        //         if (!flag) {
        //             this.getfirst()
        //         }
        //     },
        //     fail: () => {
        //         toast({title: '获取地址失败'})
        //     }
        // })
    },
    getCity: function () {
        app.ajax({
            url: '/api/index/getCity',
            data: {
                lat: this.data.lat,
                lon: this.data.lon
            },
            success: res => {
                if (res.code === 1) {
                    const city = res.data;
                    wx.setStorageSync('city', city);
                    this.setData({
                        city: city
                    });
                }
            }
        })
    },
    closeLockPop() {
        this.setData({
            showLock: false
        })
    },
    openLockHandler(ev) {
        const {detail} = ev
        this.closeLockPop()
        if (detail === LOCK_ENUM.gate) {
            this.openDoor()
            return
        }
        if (detail === LOCK_ENUM.guard) {
            this.opensmall()
        }
    },
    // getStores: function () {
    //     return
    //     app.ajax({
    //         url: '/api/index/stores',
    //         data: {
    //             lat: this.data.lat + ',' + this.data.lon,
    //             lon: this.data.lat + ',' + this.data.lon,
    //             city_id: this.data.city.id
    //         },
    //         success: res => {
    //             if (res.code == 1) {
    //                 wx.setStorageSync('stores', res.data);
    //                 this.setData({
    //                     lat: res.data[0].lat.split(',')[0],
    //                     lon: res.data[0].lon.split(',')[1],
    //                     stores: res.data
    //                 })
    //                 var markers = [];
    //                 for (var i in res.data) {
    //                     var row = res.data[i];
    //                     if (row.rooms.length > 0) {
    //                         markers.push({
    //                             id: row.rooms[0].id,
    //                             latitude: parseFloat(row.lat.split(',')[0]),
    //                             longitude: parseFloat(row.lon.split(',')[1]),
    //                             iconPath: '/images/marker.png',
    //                             width: 24,
    //                             height: 23,
    //                             callout: {
    //                                 content: `${row.name}\n ${row.address} \n 距您 ${row.distance}`,
    //                                 color: '#fff',
    //                                 fontSize: 12,
    //                                 borderRadius: 10,
    //                                 bgColor: '#00B5DB',
    //                                 padding: 5,
    //                                 display: 'ALWAYS'
    //                             }
    //                         });
    //                     }
    //                 }
    //                 this.setData({
    //                     markers: markers
    //                 })
    //             } else {
    //                 wx.removeStorageSync('stores');
    //                 // wx.showToast({
    //                 //     title: '当前城市暂无茶社',
    //                 //     icon: 'none'
    //                 // })
    //                 this.setData({
    //                     markers: []
    //                 })
    //             }
    //         }
    //     })
    // },
    onShow: function () {
        const {firstStore} = this.data
        if (firstStore.id) {
            const {id} = firstStore
            this.findRooms(id)
            this.getBanner(id);
        }
    },
    changeStoreSuccess(store) {
        this.setData({
            firstStore: store
        })
        wx.setStorageSync('firststore',store)
    },
    getNewOrder: function () {
        app.ajax({
            url: '/api/user/newOrder',
            success: res => {
                if (res.code == 1) {
                    this.setData({
                        order_id: res.data
                    })
                }
            }
        })
    },
    toStore(e) {
        var id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '/pages/search_store/search_store?id=' + id
        })
    },
    onClose() {
        this.setData({
            show: false,
        })
    },
})
